<?php


namespace app\api\controller\User;


use app\api\controller\AppController;
use app\api\model\Banner\BannerModel;
use app\api\model\Order\OrderGoodsModel;
use app\api\model\Order\OrderModel;
use app\api\model\User\UserIntegralBillModel;
use app\api\model\User\UserLevelModel;
use app\api\model\User\UserModel;
use app\api\model\User\UserAmountBillModel;
use app\api\model\User\UserWalletModel;
use app\api\model\User\UserWatchLogModel;
use app\api\validate\UserValidate;
use app\Request;
use app\Utils\ImageUtil;
use app\Utils\Util;
use think\exception\ValidateException;

class User extends AppController
{

    /**
     * 测试退款
     * @return array
     */
    public function zfbRefund(Request $request)
    {
        $param = $request->param();
        $trade_no = $param['trade_no'];
        $amount = 0.01;
        $flag = $this->aliRefund($amount, $trade_no);
        return Util::returnJson(self::CODE_SUCCESS, $flag);
    }

    /**
     * @api {get} /get_user_info 获取用户信息
     * @apiGroup 用户
     * @apiParam {string} token Token
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiSuccessExample {json} 部分数据
     * {
     *   "id":"用户ID",
     *   "account":"用户账户",
     *   "token":"用户token",
     *   "mobile":"手机号",
     *   "level_id":"会员ID 0：普通用户 2：年会员 3: 季卡会员 4：永久会员 ",
     *   "is_level_type":"是否永久会员 0：不是 1：是",
     *   "end_time":"会员到期时间",
     *   "head_img":"头像",
     *   "nickname":"昵称",
     *   "invite_code":"邀请码",
     *   "is_partner":"是否创业合伙人 0：不是 1：是",
     *   "is_activate":"1:激活码激活，无法享受分销",
     *   "wx_name":"提现微信用户名",
     *   "wx_account":"提现微信账户",
     *   "zfb_name":"支付宝提现用户名",
     *   "zfb_account":"支付宝提现支付宝账号",
     *   "reward":"总收入",
     *   "amount":"余额（可提现）",
     *   "referrals":"邀请人数",
     *   "order":{"pull_count":"待付款数量","send_count":"待发货数量","take_count":"待收货数量",},
     *   "contact_way":"联系方式",
     *   "advert_list":{"id":"会员中心广告ID","title":"标题","type_id":"类型ID","img":"图片","link_url":"链接地址"},
     *   "invite_amount":"邀请总收益",
     *   "level_info":"等级信息",
     * }
     * @apiVersion 1.0.0
     */
    public function getUserInfo(Request $request)
    {
        $user = $this->user;
        if (empty($user)) {
            return Util::returnJson(self::CODE_LOGIN, null, "请登录");
        }
        $user = UserModel::getUserWhereJoin([['u.id', '=', $user['id']]], 'u.*,uw.reward,uw.amount,uw.study_amount,uw.referrals');
        $user['head_img'] = ImageUtil::i()->replaceUrl($user['head_img']);
        //待付款
        $pull_count = OrderModel::getOrderListWhereCount([['uid', '=', $user['id']], ['status', '=', 0]]);
        //待发货
        $send_count = OrderModel::getOrderListWhereCount([['uid', '=', $user['id']], ['status', '=', 1]]);
        //待收货
        $take_count = OrderModel::getOrderListWhereCount([['uid', '=', $user['id']], ['status', '=', 2]]);
        $user['order']['pull_count'] = $pull_count;
        $user['order']['send_count'] = $send_count;
        $user['order']['take_count'] = $take_count;

        //客服
        if (!empty($this->setting)) {
            $sys_extend = json_decode($this->setting['sys_extend'], true);
            $user['contact_way'] = $sys_extend['contact_way'];
        } else {
            $user['contact_way'] = "";
        }

        if (empty($user['head_img'])) {
            //默认头像
            if (!empty($this->setting['default_head'])) {
                $user['head_img'] = ImageUtil::i()->replaceUrl($this->setting['default_head']);
            }
        }

        //个人中心广告
        $user['advert_list'] = BannerModel::getBannerWhereMore([['type_id', '=', 5], ['is_show', '=', 1]], "id,title,type_id,img,link_url");
        foreach ($user['advert_list'] as &$banner) {
            $banner['img'] = ImageUtil::i()->replaceUrl($banner['img']);
        }
        //邀请人收益
        $amount = UserWalletModel::getUserWalletBillSum([['uid', '=', $user['id']], ['bill_type', '=', 1], ['bill_use_type', '=', 3]]);
        $user['invite_amount'] = $amount;

        //会员等级
        $level = UserLevelModel::getUserLevelWhere([['id', '=', 2]], "id,level_name,price,cost_price");
        $user['level_info'] = $level;

        return Util::returnJson(self::CODE_SUCCESS, $user);
    }

    /**
     * @api {get} /get_user_wallet_list 余额/学习金记录/积分列表
     * @apiGroup 用户
     * @apiParam {string} token Token
     * @apiParam {int} page 页码
     * @apiParam {int} limit 数据条数
     * @apiParam {int} type 类型 1：余额 3：积分
     * @apiParam {int} bill_type 1收入 5支出
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getUserWalletList(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if (empty($user)) {
            return Util::returnJson(self::CODE_LOGIN, null, "请登录");
        }
        $where = [
            ['uid', '=', $user['id']]
        ];

        try {
            validate(UserValidate::class)->scene('wallet_list')->check($param);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return Util::returnJson(self::CODE_ERROR, null, $e->getError());
        }

        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;
        $type = !empty($param['type']) ? $param['type'] : 1;
        $bill_type = !empty($param['bill_type']) ? $param['bill_type'] : 1;
        if (!empty($bill_type)) {
            array_push($where, ['bill_type', '=', $bill_type]);
        } else {
            array_push($where, ['bill_type', '=', 5]);
        }
        if ($type == 1) {
            $list = UserAmountBillModel::getUserWalletBillListWhere($page, $limit, $where);
            $count = UserAmountBillModel::getUserWalletBillCountWhere($where);
        }

        if ($type == 3) {
            $list = UserIntegralBillModel::getUserIntegralBillListWhere($page, $limit, $where);
            $count = UserIntegralBillModel::getUserIntegralBillCountWhere($where);
        }
        return Util::returnPageJson(self::CODE_SUCCESS, $count, $list);
    }

    /**
     * @api {get} /get_user_watch_list 获取用户观看记录
     * @apiGroup 用户
     * @apiParam {string} token Token
     * @apiParam {int} page 页码
     * @apiParam {int} limit 数据条数
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiSuccessExample {json} 部分数据
     *  "data":[{
     *   "id":"视频ID",
     *   "video_title":"标题",
     *   "img":"图片",
     *   "label":"标签数组",
     *   "brief":"描述",
     *   "play_num":"播放量",
     *   "play_default":"默认播放量",
     *   "is_recommend":"是否推荐 1：推荐"
     * }]
     * @apiVersion 1.0.0
     */
    public function getUserWatchList(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if (empty($user)) {
            return Util::returnJson(self::CODE_LOGIN, null, "请登录");
        }
        $where = [
            ['uwl.uid', '=', $user['id']]
        ];
        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;
        $list = UserWatchLogModel::getUserWatchLogListWhere($page, $limit, $where);
        $count = UserWatchLogModel::getUserWatchLogCountWhere($where);
        foreach ($list as &$item) {
            $item['label'] = !empty($item['label']) ? json_decode($item['label'], true) : [];
            $item['img'] = ImageUtil::i()->replaceUrl($item['img']);
            $images = !empty($item['slider_img']) ? json_decode($item['slider_img'], true) : [];
            foreach ($images as &$image) {
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $item['slider_img'] = $images;
            //$item['details'] = !empty($item['details']) ? htmlspecialchars_decode($item['details']) : "";
        }
        return Util::returnPageJson(self::CODE_SUCCESS, $count, $list);
    }

    /**
     * @api {post} /update_password 用户修改密码
     * @apiGroup 用户
     * @apiParam {string} token Token
     * @apiParam {string} password 旧密码
     * @apiParam {string} repassword 新密码
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function updatePassword(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if (empty($user)) {
            return Util::returnJson(self::CODE_LOGIN, null, "请登录");
        }
        try {
            validate(UserValidate::class)->scene('update_password')->check($param);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return Util::returnJson(self::CODE_ERROR, null, $e->getError());
        }

        $password = $param['password'];
        $repassword = $param['repassword'];

        if (md5($password) == $user['password']) {
            $save = [
                'password' => md5($repassword),
                'token' => "",
                'up_time' => date("Y-m-d H:i:s", time())
            ];
            $flag = UserModel::updateUserWhere([['id', '=', $user['id']]], $save);
            if ($flag) {
                return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
            } else {
                return Util::returnJson(self::CODE_ERROR, null, "修改失败");
            }
        } else {
            return Util::returnJson(self::CODE_ERROR, null, "旧密码不正确");
        }
    }

    /**
     * @api {get} /get_invite_list 我的邀请人列表
     * @apiGroup 用户
     * @apiParam {string} token Token
     * @apiParam {int} page 页码
     * @apiParam {int} limit 数据条数
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getInviteList(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if (empty($user)) {
            return Util::returnJson(self::CODE_LOGIN, null, "请登录");
        }
        $where = [
            ['parent_uid', '=', $user['id']]
        ];
        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;
        $list = UserModel::getUserListWhere($page, $limit, $where, "id,account,mobile,level_id,head_img,nickname,add_time");
        $count = UserModel::getUserCountWhere($where);
        foreach ($list as &$item) {
            $item['head_img'] = ImageUtil::i()->replaceUrl($item['head_img']);
            $order_goods_list = OrderGoodsModel::getOrderGoodsListWhereMoreJoin([['o.uid', '=', $item['id']], ['og.status', '=', 3]], "og.agnet_uid1,og.agent_amount1");
            $agent_amount = 0;
            foreach ($order_goods_list as $value) {
                if ($value['agnet_uid1'] == $user['id']) {
                    $agent_amount += $value['agent_amount1'];
                }
            }
            $item['agent_amount'] = $agent_amount;
        }
        unset($item);
        return Util::returnPageJson(self::CODE_SUCCESS, $count, $list);
    }

    /**
     * @api {get} /build_user_withdraw_account 绑定提现账号
     * @apiGroup 用户
     * @apiParam {string} token Token
     * @apiParam {int} type 2:支付宝 3：微信
     * @apiParam {string} name 提现名字
     * @apiParam {string} withdraw_account 提现账户
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function buildUserWithdrawAccount(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if ($param['type'] == 2) {
            $data = [
                'zfb_name' => $param['name'],
                'zfb_account' => $param['withdraw_account']
            ];
        }
        if ($param['type'] == 3) {
            $data = [
                'wx_name' => $param['name'],
                'wx_account' => $param['withdraw_account']
            ];
        }
        $flag = UserModel::updateUserWhere([['id', '=', $user['id']]], $data);
        if ($flag) {
            return Util::returnJson(self::CODE_SUCCESS, null, "修改成功！");
        } else {
            return Util::returnJson(self::CODE_ERROR, null, "修改失败！");
        }
    }

    /**
     * @api {post} /edit_user_info 修改信息
     * @apiGroup 用户
     * @apiParam {string} token Token
     * @apiParam {string} nickname 用户昵称
     * @apiParam {file} file
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function editUserInfo(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if (empty($user)) {
            return Util::returnJson(self::CODE_ERROR, null, "请登录");
        }
        //图片上传(单图)
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "user/head/" . $user['id'] . "/";
            $url = ImageUtil::i()->upload($file, $path);
        }
        $data = [];
        if (!empty($url)) {
            $data['head_img'] = $url;
        }
        if (!empty($param['introduce'])) {
            $data['introduce'] = $param['introduce'];
        }
        if (!empty($param['nickname'])) {
            $data['nickname'] = trim($param['nickname']);
        }
        $flag = UserModel::updateUserWhere([['id', '=', $user['id']]], $data);
        if ($flag) {
            return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
        } else {
            return Util::returnJson(self::CODE_ERROR, null, "修改失败");
        }
    }

    /**
     * @api {get} /user/get_share 分享获取数据
     * @apiGroup 用户
     * @apiParam {string} token Token
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getShare(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if (empty($user)) {
            return Util::returnJson(self::CODE_LOGIN, null, "请登录");
        }
        $url = $this->setting['img_url'] . "/api/user/invite?invite=" . $user['invite_code'];
        $data['url'] = $url;
        $data['invite_code'] = $user['invite_code'];
        return Util::returnJson(self::CODE_SUCCESS, $data);

    }

}